﻿using BarcodeDelay.bean;
using BarcodeDelay.FrameDecoder;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace BarcodeDelay.business
{
    public class CancelOrderHelperGen
    {
        private StreamWriter swb = null;
        FileStream bFile = null;
        ArrayList m_arListCancelsBarcodes = new ArrayList();
        public event Action CancelsEvent;

        private static CancelOrderHelperGen instance;
        public static CancelOrderHelperGen Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new CancelOrderHelperGen();
                }
                return instance;
            }
        }
        private Thread fThreadDep = null;
        public void BeginAnalyThread(ArrayList arListBarCodes)
        {
            try
            {
                initLog();
                m_arListCancelsBarcodes.Clear();
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    fThreadDep.Abort();
                    System.Threading.Thread.Sleep(50);
                }
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    while (fThreadDep.ThreadState != ThreadState.Aborted)
                    {
                        //当调用Abort方法后，如果thread线程的状态不为Aborted，主线程就一直在这里做循环，直到thread线程的状态变为Aborted为止
                        Thread.Sleep(100);
                    }
                }


                m_arListCancelsBarcodes = arListBarCodes;
                fThreadDep = new Thread(new ParameterizedThreadStart(parseCancels));
                fThreadDep.Start((object)arListBarCodes);

                fThreadDep.IsBackground = true;
              

            }
            catch (Exception ex)
            {

            }
        }



        public void parseCancels(object arListBarcodes)
        {
            //StoParams.Instance.htResWechat.Clear();
            string resMsg = "";
            int totalDelays = 0;
            int queryServerResTime = 0;
            int priorBarCodeCount = 0;
            ArrayList arListDepResultTmp = new ArrayList();
            try
            {
                int totalQueryCount = 0;
                ArrayList arListTmp = new ArrayList();
                RoadInfo roadInfoGen = new bean.RoadInfo();
                Hashtable htRoadMap = new Hashtable();
                ArrayList arListBarCodes = new ArrayList();
                arListBarCodes.Clear();
                DateTime dtStart = System.DateTime.Now;
                JArray wayBills = new JArray();
                string lastBarcode = "";
                foreach (ParcelBean parcelBean in (ArrayList)arListBarcodes)
                //foreach (string strBarCode in (ArrayList)arListBarcodes)
                {
                    string strBarCode = parcelBean.wayBill;
                    wayBills.Add(strBarCode.Trim());
                    lastBarcode = strBarCode.Trim();
                    string pickName = "";
                    string orderSource = "";
                    string curSiteToken = "";
                    string customerName = "";
                    if (!UtilityHelp.Instance.resetToken(strBarCode.Trim(),out pickName,out orderSource,out curSiteToken,out customerName))
                    {
                        if (curSiteToken == "")
                        {
                            FrameDecoderManager.Instance.htFailedParcel[strBarCode] = System.DateTime.Now;
                            StoParams.Instance.htResWechat[strBarCode] = " 发件网点 " + pickName + " 登录失效";
                            continue;
                        }
                        StoParams.Instance.htResWechat[lastBarcode] = " 发件网点 "+ pickName+ " 非我司单号  无法处理";
                        return;
                    }

                    parcelBean.lanshouSite = pickName;
                    parcelBean.customerName = customerName;
                    JObject jObjDetail = new JObject();
                    jObjDetail["siteCode"] = StoParams.Instance.regCode;
                    jObjDetail["startDate"] = System.DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd") + " " + "00:00:00";
                    jObjDetail["endDate"] = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    jObjDetail["codeType"] = 2;
                    jObjDetail["p_billType"] = "1";
                    jObjDetail["p_billNo"] = strBarCode.Trim();
                    jObjDetail["current"] = 1;
                    jObjDetail["size"] = 20;
                    jObjDetail["inputTimeSort"] = false;
                    jObjDetail["countryId"] = "1";

                    string strUrl = "https://jmsgw.jtexpress.com.cn/customerplatform/omsOrderStatus/statusQuery";

                    if(StoParams.Instance.isRabbitWin)
                    {
                        strUrl = "https://wdgw.jtexpress.com.cn/wdccmorderweb/omsOrderStatus/statusQuery";
                    }
                    string postData = "";
                    string res = "";
                    //if (!StoParams.Instance.isRabbitWin)
                    {
                        postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObjDetail);
                        res = HttpClient.HttpUtil.Instance.PostCommonByToken(strUrl, postData, "orderTracking", curSiteToken);

                        StoParams.Instance.resMsg = "";
                        parcelBean.replyType = "订单取消";
                        JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(res);
                        if (!res.Contains("请求成功"))
                        {
                            if (res.Contains("msg"))
                            {

                                JToken msgToken = jsonObjRes["msg"];
                                res = msgToken.ToString();
                            }
                            if (!parcelBean.isAutoCancel)
                            {
                                StoParams.Instance.htResWechat[lastBarcode] = " 取消订单失败 " + res;
                            }

                            StoParams.Instance.curFailedBarcode = lastBarcode;
                            StoParams.Instance.resMsg = lastBarcode + " 取消订单失败 " + res;


                            continue;

                        }


                        JObject jsonObjData = (JObject)jsonObjRes["data"];
                        JArray records = (JArray)jsonObjData["records"];
                        if (records.Count == 0)
                        {
                            continue;
                        }
                        string signStieCode = "";
                        long waybillID = 0;
                        for (int i = 0; i < records.Count; i++)
                        {
                            JObject json = (JObject)records[i];
                            JToken id = json["id"];
                            if (id != null)
                            {
                                waybillID = long.Parse(id.ToString());
                            }
                        }

                        if (waybillID == 0)
                        {
                            continue;
                        }
                        JArray idsArray = new JArray();
                        idsArray.Add(waybillID.ToString());

                        jObjDetail = new JObject();
                        jObjDetail["cancelExplain"] = "";
                        jObjDetail["cancelReasonCode"] = 1;
                        jObjDetail["countryId"] = "1";
                        jObjDetail["ids"] = idsArray;

                    }
                    
                    

                    strUrl = "https://jmsgw.jtexpress.com.cn/customerplatform/omsOrderDispatch/cancleOrder";
                    if (StoParams.Instance.isRabbitWin)
                    {
                        strUrl = "https://wdgw.jtexpress.com.cn/wdccmorderweb/omsOrderDispatch/cancleOrder";
                    }
                    string routerName = "orderTracking";
                    /*if (StoParams.Instance.isRabbitWin)
                    {
                        jObjDetail = new JObject();
                        jObjDetail["countryId"] = "1";
                        jObjDetail["reason"] = "客户取消寄件";
                        jObjDetail["pickNetworkName"] = StoParams.Instance.register_site;
                        jObjDetail["username"] = StoParams.Instance.register_user;
                        jObjDetail["pickNetworkCode"] = StoParams.Instance.register_code;
                        JArray jarWaybill = new JArray();
                        jarWaybill.Add(strBarCode);
                        jObjDetail["waybillNos"] = jarWaybill;
                        strUrl = "https://wdgw.jtexpress.com.cn/ops/wdbutler/cancelRegist/addOrderCancel";
                        routerName = "cancelExpress";
                    }*/

                    postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObjDetail);
                    res = HttpClient.HttpUtil.Instance.PostCommonByToken(strUrl, postData, routerName, curSiteToken);
                    if (!res.Contains("请求成功"))
                    {
                        if (res.Contains("msg"))
                        {
                            JObject jsonObjResLast = (JObject)JsonConvert.DeserializeObject(res);
                            JToken msgToken = jsonObjResLast["msg"];
                            res = msgToken.ToString();
                        }

                        if (!parcelBean.isAutoCancel)
                        {
                            StoParams.Instance.htResWechat[lastBarcode] = " 取消订单失败 " + res;
                        }
                           
                        StoParams.Instance.curFailedBarcode = lastBarcode;
                        StoParams.Instance.resMsg = lastBarcode + " 取消订单失败 " + res;
                        continue;
                    }
                    else
                    {
                        //if(!parcelBean.isAutoCancel)
                        {
                            StoParams.Instance.htResWechat[lastBarcode] = " 取消订单成功";
                        }
                        if (parcelBean.isAutoCancel)
                        {
                            StoParams.Instance.htResWechat[lastBarcode] = " 拦截成功，取消订单成功";
                            parcelBean.replyType = "拦截无物流";
                        }

                        if (StoParams.Instance.register_site.Contains("曹三") || StoParams.Instance.register_site.Contains("菊城"))
                        {
                            StoParams.Instance.htResWechat[lastBarcode] = " 订单已取消";
                        }

                    }

                    //StoParams.Instance.htResWechat[lastBarcode] = resMsg;

                }



            }
            catch (Exception ex)
            {
                

            }
            int tiot = queryServerResTime;
           


        }






        public void stopThread()
        {
            try
            {
                ArrayList arListT = new ArrayList();
                ResultBean resultBean = new ResultBean();
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    /*if (totalQueryCount > 0)
                    {
                        resultBean.countTime = totalQueryCount;

                        updateQueryCount(resultBean);
                    }*/
                    fThreadDep.Abort();
                    if (swb != null)
                    {
                        swb.Close();
                    }

                }

    
            }
            catch (Exception ex)
            {

            }
        }


        private void initLog()
        {
            try
            {
                string dir = System.Environment.CurrentDirectory;
                bFile = new FileStream(dir + "\\error.txt", FileMode.Create);
                if (swb == null)
                {
                    swb = new StreamWriter(bFile);
                    swb.WriteLine("begin");

                }
            }
            catch (Exception ex)
            {

            }

        }


    }
}
